# --- 创建
# 通过 {} 、dict() 来创建
d1 = {"name": "yesen", "age": 18, "job": "programmer"}
d2 = dict(name="yesen", age=18, job="programmer")
d3 = dict([("name", "yesen"), ("age", 18)])
d4 = {}
d5 = dict()

print(d1, d2, d3, d4, d5)

# 通过 zip() 创建
keys = ["name", "age", "job"]
vals = ("yesen", 18, "programmer")
d = dict(zip(keys, vals))
print(d)

# 通过 fromkeys() 创建值为空的字典
d = dict.fromkeys(["name", "age", "job"])
print(d)

# --- 获取值
# 通过`[键]`的方式，如果键不存在，报错
print(d1["name"])
# print(d1["not_exists"]) # 报错

# 通过 `get()` 方法，如果键不存在，返回 `None` 或默认值【💕推荐使用】
print(d1.get("name"))
print(d1.get("not_exists", "foo"))

# 获取所有键、值
print(d1.keys(), d1.values(), d1.items())

# 某个键是否存在于字典中
print("name" in d1)

# --- 字典元素的增、删、改
# 如果键已存在，则修改；如果不存在，则添加
d1["name"] = "张三"
d1["address"] = "火星"
print(d1)

# `update()` 方法：如果键已存在，则覆盖；如果不存在，则添加
foo = {"phone": "123456", "mail": "yesen@mail.io", "name": "yesen"}
d1.update(foo)
print(d1)

# 删除
phone = d1.pop("phone")
print(phone, d1)

item = d1.popitem()  # 随机删除一项。因为字典无序，所以没有首尾的概念
print(item, d1)

# del(d1["job"])
# print(d1)

# 清空
# d1.clear()
# print(d1)

# --- 解包
d = {"name": "yesen", "age": 18, "job": "programmer"}

# 对键进行解包(默认)
# name, age, job = d
# print(name, age, job)
k1, k2, k3 = d
print(k1, k2, k3)

# 对值进行解包
name, age, job = d.values()
print(name, age, job)

# 对键值对进行解包
name, age, job = d.items()
print(name, age, job)

# --- 存储表格数据
employes = [
    {"name": "张三", "age": 18, "salary": 3000, "city": "上海"},
    {"name": "李四", "age": 28, "salary": 7621, "city": "深圳"},
    {"name": "王五", "age": 23, "salary": 17213, "city": "广州"},
]
print("姓名\t年龄\t薪资\t城市")
print("-----------------------------")
for employe in employes:
    print(
        "{0}\t{1}\t{2}\t{3}".format(
            employe["name"],
            employe["age"],
            employe.get("salary", 0),
            employe.get("city", "火星"),
        )
    )
